package com.wxsoft.business.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.wxsoft.business.common.controller.BaseController;
import com.wxsoft.business.model.easyui.DataGrid;
import com.wxsoft.business.model.easyui.PageHelper;
import com.wxsoft.business.model.easyui.TreeForCombo;
import com.wxsoft.business.sys.pojo.SysUnitInfo;
import com.wxsoft.business.sys.pojo.SysUser;
import com.wxsoft.business.sys.service.ISysUnitInfoService;
import com.wxsoft.frame.cache.UnitCache;
import com.wxsoft.util.JsonUtil;
import com.wxsoft.util.UserUtil;
import com.wxsoft.util.common.Const;
import com.wxsoft.util.common.HanyuPinyinHelper;

@Controller
@RequestMapping("/sysUnitInfo")
public class SysUnitInfoController extends BaseController{
	
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Resource
	private ISysUnitInfoService service;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		return "sys/sysUnitInfolist";
	}

    @ResponseBody
	@RequestMapping("/datagrid")
	public DataGrid list(HttpServletRequest request,PageHelper page, SysUnitInfo sysUnitInfo,HttpServletResponse response) throws IOException{

    	//设置用户所在单位，根据用户所在单位，查询 所在单位，或其 所在单位 的 子单位的信息
		SysUser user = UserUtil.getUser(request);
    	sysUnitInfo.setUnit_idUser(user.getUnit_id());
    	
		DataGrid dg = new DataGrid();
		dg.setTotal(service.findCount(sysUnitInfo));
		List<SysUnitInfo> sysUnitInfoList = service.findAll(page, sysUnitInfo);
		dg.setRows(sysUnitInfoList);
//		JsonUtil.toResponse(response, dg);
		return dg ;
	}
	
	@ResponseBody
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public void add(HttpServletRequest request,HttpServletResponse response, SysUnitInfo sysUnitInfo) {
		try {
			//设置单位缓存为空
			UnitCache.setUnitTreeForCombo(null);
			
			SysUser user = UserUtil.getUser(request);
			sysUnitInfo.setHandle(user.getUser_id());
			sysUnitInfo.setHandle_date(new Date());
			String r = service.add(sysUnitInfo);
			this.writeReturn(request,response, r);
		} catch (Exception e) {
			e.printStackTrace();
			this.writeReturn(request,response, false, e.getMessage());
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/modify", method = RequestMethod.POST)
	public void modify(HttpServletRequest request,HttpServletResponse response, SysUnitInfo sysUnitInfo) {
		try {
			//设置单位缓存为空
			UnitCache.setUnitTreeForCombo(null);

			SysUser user = UserUtil.getUser(request);
			sysUnitInfo.setHandle(user.getUser_id());
			sysUnitInfo.setHandle_date(new Date());
			String r = service.modify(sysUnitInfo);
			this.writeReturn(request,response, r);
		} catch (Exception e) {
			e.printStackTrace();
			this.writeReturn(request,response, false, e.getMessage());
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void delete(HttpServletRequest request,HttpServletResponse response, SysUnitInfo sysUnitInfo) {
		try {
			//设置单位缓存为空
			UnitCache.setUnitTreeForCombo(null);
			String r = service.delete(sysUnitInfo);
			this.writeReturn(request,response, r);
		} catch (Exception e) {
			e.printStackTrace();
			this.writeReturn(request,response, false, e.getMessage());
		}
	}
	/**
	 * 转到审核列表
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/examineList", method = RequestMethod.GET)
	public String examineList(Model model) {
		return "sys/sysUnitInfoExamine";
	}
	@ResponseBody
	@RequestMapping(value = "/examine", method = RequestMethod.POST)
	public void examine(HttpServletRequest request,HttpServletResponse response, SysUnitInfo sysUnitInfo) {
		try {
			
			SysUser user = UserUtil.getUser(request);
			sysUnitInfo.setExamine(user.getUser_id());
			sysUnitInfo.setExamine_date(new Date());
			
			String r = service.examine(sysUnitInfo);
			
			this.writeReturn(request,response, r);
		} catch (Exception e) {
			e.printStackTrace();
			this.writeReturn(request,response, false, e.getMessage());
		}
	}
	

	/**
	 * 获取所有菜单树
	 * @param session
	 * @return
	 */
    @RequestMapping(value="/getBy")  
    public void getBy(HttpSession session, HttpServletResponse response, SysUnitInfo sysUnitInfo){
    	String treeStr = UnitCache.getUnitTreeForCombo();
    	if(null==treeStr || "".equals(treeStr)){
	    	SysUser user =  (SysUser)session.getAttribute(Const.SESSION_USER); 
	    	List<SysUnitInfo> list = service.getBy(sysUnitInfo);
	    	List<TreeForCombo> treeList = getTree(list);
	        String json=JSONArray.toJSONString(treeList);
//	        System.out.println(json);
	        UnitCache.setUnitTreeForCombo(json);
	        treeStr = json;
    	}
		JsonUtil.toResponse(response, treeStr);
//    	return menuTreeStr;
    }
    
    /**
     * 将菜单变成树形结构
     * @param menuList
     * @return
     */
    public List<TreeForCombo> getTree(List<SysUnitInfo> list){
    	List<TreeForCombo> treeFList = new ArrayList<TreeForCombo>();
    	
		TreeForCombo nodeF = new TreeForCombo();
		nodeF.setId("0");
		nodeF.setText("顶级单位");
		nodeF.setPyFirst(HanyuPinyinHelper.getFirstLettersLo("顶级单位"));
		nodeF.setPyFull(HanyuPinyinHelper.getFullLettersLo("顶级单位"));
		addNode(nodeF, list);
		
    	treeFList.add(nodeF);
    	return treeFList ; 
    }
    public void addNode(TreeForCombo pNode, List<SysUnitInfo> list){
    	List<TreeForCombo> treeList = new ArrayList<TreeForCombo>();

    	for(SysUnitInfo cNode : list){
    		//如果子节点父ID=父节点ID
    		if(pNode.getId().equals(cNode.getHigher_unit_id())){

    			TreeForCombo node = new TreeForCombo();
    			
    			node.setId(cNode.getUnit_id());
//    			node.setPid(menu.getPcode());
    			node.setText(cNode.getFull_name());
    			node.setPyFirst(HanyuPinyinHelper.getFirstLettersLo(cNode.getFull_name()));
    			node.setPyFull(HanyuPinyinHelper.getFullLettersLo(cNode.getFull_name()));
    			treeList.add(node);
    			addNode(node, list);
    		}
    		
    	}
    	pNode.setChildren(treeList);
    }

}
